package com.briup.cloud.framework.resource.config;

import feign.RequestInterceptor;
import lombok.extern.slf4j.Slf4j;
//import okhttp3.OkHttpClient;
//import okhttp3.Request;
//import okhttp3.Response;
//import okhttp3.ResponseBody;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.Servlet;
import javax.servlet.http.HttpServletRequest;
import java.util.Enumeration;

/**
 * @Author guomiao
 * @Date 2022/4/11 16:33
 */
@Configuration
@Slf4j
public class FeignConfig {

    @Value("Authorization")
    private String tokenHeader;

    @Bean
    public RequestInterceptor requestInterceptor(){
        log.debug("设置fegin请求的请求头");
        return restTemplate -> {
            RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
//            System.out.println("requestAttributes:==================>"+requestAttributes);
            if(requestAttributes instanceof ServletRequestAttributes) {
                ServletRequestAttributes attrs = (ServletRequestAttributes) requestAttributes;
                //System.out.println("设置： " + attrs);
                if (attrs != null) {
                    HttpServletRequest request = attrs.getRequest();
                    String tokenVal = request.getHeader(tokenHeader);
//                    System.out.println(tokenHeader+" --------------------->"+tokenVal);
                    log.debug(tokenHeader, tokenVal);
                    restTemplate.header(tokenHeader, tokenVal);
                }
            }else{
                restTemplate.header(tokenHeader,TokenHolder.getCurrentToken());
            }
        };
    }


}
